# authentication/serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
from product.models import UserProfile
from django.contrib.auth import authenticate

class RegisterSerializer(serializers.ModelSerializer):
    phone = serializers.CharField(write_only=True, required=True)
    smsCode = serializers.CharField(write_only=True, required=True)
    confirmPassword = serializers.CharField(write_only=True, required=True)
    
    class Meta:
        model = User
        fields = ['username', 'password', 'phone', 'smsCode', 'confirmPassword']
        extra_kwargs = {'password': {'write_only': True}}

    def validate(self, data):
        if data['password'] != data['confirmPassword']:
            raise serializers.ValidationError("密码和确认密码不匹配")
        
        # 验证码检查（根据需求，验证码可以任意输入，这里只检查长度）
        if len(data['smsCode']) != 6:
            raise serializers.ValidationError("验证码必须是6位")
            
        return data

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password']
        )
        # 信号处理器会自动创建UserProfile，这里只需要更新手机号
        user_profile = UserProfile.objects.get(user=user)
        user_profile.phone = validated_data['phone']
        user_profile.save()
        return user

class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate(self, data):
        phone = data.get('phone')
        password = data.get('password')

        if not phone or not password:
            raise serializers.ValidationError("请输入手机号和密码。")

        try:
            user_profile = UserProfile.objects.get(phone=phone)
            user = user_profile.user
            
            if user and user.is_active and user.check_password(password):
                return user
            else:
                raise serializers.ValidationError("手机号或密码不正确。")
                
        except UserProfile.DoesNotExist:
            raise serializers.ValidationError("手机号或密码不正确。")